package com.dk.filter;

import com.alibaba.fastjson.JSONObject;
import com.dk.data.Result;
import com.dk.em.ConstantEnum;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName RequestFilter  限流的过滤器
 * @Deacription TODO
 * @Author hqq
 * @Date 2021/10/25 17:54
 * @Version 1.0
 **/
@Component
public class RequestFilter extends ZuulFilter {

    //每秒产生1000个令牌
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(3);

    /**
     * 配置过滤类型，有四种不同生命周期的过滤器类型
     * 1. pre：路由之前
     * 2. routing：路由之时
     * 3. post：路由之后
     * 4. error：发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    //网关可以写多个过滤器.这个表示过滤器执行的顺序,数字越小,越先执行
    @Override
    public int filterOrder() {
        return 0;
    }

    //过滤器开关
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        System.out.println("获取令牌");
        //尝试获取令牌,取到就返回true,取不到就返回false
        boolean tryAcquire = RATE_LIMITER.tryAcquire();
        // 如果获取不到就直接停止
        if(!tryAcquire){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(ConstantEnum.TOO_QUICKLY.getCode());
            //获取response
            HttpServletResponse response = requestContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                Result result = Result.bulid(ConstantEnum.TOO_QUICKLY);
                response.getWriter().write(JSONObject.toJSONString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
